package cn.sjtu.security.handler;

import cn.sjtu.security.utils.GlobalConstants;
import cn.sjtu.security.utils.JwtUtils;
import cn.sjtu.security.vo.HttpResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.sjtu.security.utils.GlobalConstants.LOGIN_TOKEN_EXPIRE;

/**
 * 认证成功处理器，当认证成功需要生成一个token，用户将会使用这个token
 */

@Component
@Slf4j
public class AuthenticationSuccessfulHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//        HttpResult httpResult = HttpResult.builder().code(1).msg("登录成功！").build();
//
//        String s = objectMapper.writeValueAsString(httpResult);
//
//        httpServletResponse.setContentType("application/json;charset=utf-8");
//
//        PrintWriter writer = httpServletResponse.getWriter();
//        writer.write(s);
//        writer.flush();

        UserDetails principal = (UserDetails)authentication.getPrincipal();

        Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();

        List<String> auths = authorities.stream().map(item -> item.getAuthority()).collect(Collectors.toList());

        String[] strAuths = auths.toArray(new String[auths.size()]);

        // 将用户名放入了jwt
        String jwt = jwtUtils.createJwt(100, principal.getUsername(), strAuths);

        HttpResult httpResult = HttpResult.builder()
                        .code(1)
                        .msg("jwt生成成功！")
                        .data(jwt)
                        .build();


        httpServletResponse.setContentType("application/json;charset=utf-8");

        // 将jwt放在redis中, 设置过期时间和jwt的过期时间
        stringRedisTemplate.opsForValue().set(GlobalConstants.LOGIN_TOKEN_PREFIX + jwt, objectMapper.writeValueAsString(authentication),
                LOGIN_TOKEN_EXPIRE, TimeUnit.HOURS);

        objectMapper.writeValue(httpServletResponse.getOutputStream(), httpResult);
    }
}
